'
' Copyright (c) 2004
' by Peter Donker ( info@bring2mind.net )
'
' Permission is hereby granted to use and/or modify this software for a single server. It is 
' NOT permitted to publish, distribute, sublicense, and/or sell copies of this software in its
' original or modified form. You are not allowed to remove this copyright notice. Please read the
' enclosed EULA for further details.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
' BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
' NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
' DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF THE SOFTWARE.
'
Imports System.IO
Imports System.Web.Caching
Imports System.Threading
Imports System.Resources
Imports System.Collections.Specialized
Imports System.Diagnostics
Imports System.Reflection
Imports System.Xml
Imports DotNetNuke
Imports DotNetNuke.Entities.Users
Imports DotNetNuke.Services.Localization
Imports System.Globalization
Imports System.Security.Cryptography
Imports System.Drawing.Imaging

Namespace Bring2mind.DNN.Modules.Questionnaire

 Friend Module Globals

  'Public Const PermittedFileExtensions As String = ".jpg;.gif;.bmp;.tif;.tiff;"

  Friend Sub SaveFile(ByVal sFile$, ByRef sText$)
   Dim fs As System.IO.FileStream = New System.IO.FileStream(sFile$, System.IO.FileMode.Create, System.IO.FileAccess.Write)
   Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(fs)
   sw.Write(sText$)
   sw.Flush()
   sw.Close()
   fs.Close()
  End Sub

  Public Sub ParameterizeString(ByRef strString As String, ByVal objUser As UserInfo, ByVal Custom As ArrayList)

   Dim objPortalSettings As Entities.Portals.PortalSettings = Entities.Portals.PortalController.GetCurrentPortalSettings

   If strString <> "" Then

    Dim strKey As String

    ' host values
    If InStr(1, strString, "Host:", CompareMethod.Text) <> 0 Then
     Dim objHostSettings As Hashtable = Entities.Host.HostSettings.GetSecureHostSettings
     For Each strKey In objHostSettings.Keys
      If InStr(1, strString, "[Host:" & strKey & "]", CompareMethod.Text) <> 0 Then
       strString = Replace(strString, "[Host:" & strKey & "]", objHostSettings(strKey).ToString, , , CompareMethod.Text)
      End If
     Next
    End If

    ' get portal values
    If InStr(1, strString, "Portal:", CompareMethod.Text) <> 0 Then
     If Not objPortalSettings Is Nothing Then
      strString = PersonalizeSystemMessage(strString, "Portal:", objPortalSettings, GetType(Entities.Portals.PortalSettings))
     End If
     strString = Replace(strString, "[Portal:URL]", objPortalSettings.PortalAlias.HTTPAlias, , , CompareMethod.Text)
    End If

    ' get user values
    If (Not objUser Is Nothing) And (Not objPortalSettings Is Nothing) Then
     If InStr(1, strString, "User:", CompareMethod.Text) <> 0 Then
      strString = PersonalizeSystemMessage(strString, "User:", objUser, GetType(UserInfo))
      strString = Replace(strString, "[User:VerificationCode]", objPortalSettings.PortalId.ToString & "-" & objUser.UserID.ToString, , , CompareMethod.Text)
     End If
     If InStr(1, strString, "Membership:", CompareMethod.Text) <> 0 Then
      strString = PersonalizeSystemMessage(strString, "Membership:", objUser.Membership, GetType(UserMembership))
     End If
     If InStr(1, strString, "Profile:", CompareMethod.Text) <> 0 Then
      strString = PersonalizeSystemMessage(strString, "Profile:", objUser.Profile, GetType(UserProfile))
     End If
    End If

    ' custom
    If InStr(1, strString, "Custom:", CompareMethod.Text) <> 0 Then
     If Not Custom Is Nothing Then
      Dim intIndex As Integer
      For intIndex = 0 To Custom.Count - 1
       strString = Replace(strString, "[Custom:" & intIndex.ToString & "]", Custom(intIndex).ToString, , , CompareMethod.Text)
      Next intIndex
     End If
    End If

    ' constants
    Dim ci As New CultureInfo(Thread.CurrentThread.CurrentCulture.ToString.ToLower)

    strString = Replace(strString, "[Date:Current]", Now().ToString("D", ci), , , CompareMethod.Text)

   End If

  End Sub

  Private Function PersonalizeSystemMessage(ByVal MessageValue As String, ByVal Prefix As String, ByVal objObject As Object, ByVal objType As Type) As String

   Dim intProperty As Integer
   Dim strPropertyName As String
   Dim strPropertyValue As String

   Dim objProperties As ArrayList = DotNetNuke.Common.Utilities.CBO.GetPropertyInfo(objType)

   For intProperty = 0 To objProperties.Count - 1
    strPropertyName = CType(objProperties(intProperty), PropertyInfo).Name
    If InStr(1, MessageValue, "[" & Prefix & strPropertyName & "]", CompareMethod.Text) <> 0 Then
     Dim propInfo As PropertyInfo = CType(objProperties(intProperty), PropertyInfo)
     Dim propValue As Object = propInfo.GetValue(objObject, Nothing)

     If propValue Is Nothing = False Then
      strPropertyValue = propValue.ToString()
     End If

     ' special case for encrypted passwords
     If (Prefix & strPropertyName = "Membership:Password") And Convert.ToString(Common.Globals.HostSettings("EncryptionKey")) <> "" Then
      Dim objSecurity As New Security.PortalSecurity
      strPropertyValue = objSecurity.Decrypt(Common.Globals.HostSettings("EncryptionKey").ToString, strPropertyValue)
     End If

     MessageValue = Replace(MessageValue, "[" & Prefix & strPropertyName & "]", strPropertyValue, , , CompareMethod.Text)
    End If
   Next intProperty

   Return MessageValue

  End Function

  Public Function GetLocalizedFile(ByVal FilePath As String, ByVal Locale As String) As String

   If FilePath = "" Then Return ""
   If Not IO.File.Exists(FilePath) Then Return ""

   ' Get various parts
   Dim d As String = IO.Path.GetDirectoryName(FilePath) & "\"
   Dim f As String = IO.Path.GetFileNameWithoutExtension(FilePath)
   Dim e As String = IO.Path.GetExtension(FilePath)

   If IO.File.Exists(d & f & "." & Locale & e) Then
    Return d & f & "." & Locale & e
   Else
    Dim defLoc As String = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings.DefaultLanguage
    If IO.File.Exists(d & f & "." & defLoc & e) Then
     Return d & f & "." & defLoc & e
    Else
     Return FilePath
    End If
   End If

  End Function

  Private Const ValidChars As String = "ACDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

  Public Function RandomString(ByVal MinLength As Integer, ByVal MaxLength As Integer) As String
   Dim Length As Integer = MinLength + Int(Rnd() * (MaxLength - MinLength + 1))
   Dim rng As New RNGCryptoServiceProvider
   Dim buff(Length - 1) As Byte
   rng.GetBytes(buff)
   Dim i As Integer, Res As String = ""
   For i = 0 To Length - 1
    Res &= Mid(ValidChars, buff(i) Mod (62) + 1, 1)
   Next
   Return Res
  End Function

  Public Sub ResizeImage(ByVal sFilename As String, ByVal iSize As Integer, Optional ByVal DestinationPath As String = "")
   Dim thisImage As Bitmap
   Dim imgFormat As ImageFormat
   Dim sFile$, sExt$, sDir$
   Dim imgHeight As Integer, imgWidth As Integer, imgRatio As Single

   Dim fi As System.IO.FileInfo
   Dim xProp As Integer

   Try

    fi = New System.IO.FileInfo(sFilename)
    sDir$ = fi.DirectoryName
    sExt$ = fi.Extension
    sFile$ = Left$(fi.Name, Len(fi.Name) - Len(sExt$))

    thisImage = New Bitmap(sFilename)
    imgFormat = thisImage.RawFormat
    imgWidth = thisImage.Width
    imgHeight = thisImage.Height
    imgRatio = Convert.ToSingle(imgHeight / imgWidth)

    Dim backBuffer As Bitmap
    Dim backBufferGraphics As Graphics
    Dim xNewHeight As Integer, xNewWidth As Integer
    Dim xScale As Single

    If imgRatio > 1 Then
     xScale = Convert.ToSingle(iSize / imgHeight)
    Else
     xScale = Convert.ToSingle(iSize / imgWidth)
    End If
    If xScale > 1 Then
     fi = Nothing
     thisImage.Dispose()
     Exit Sub
    End If
    xNewHeight = Convert.ToInt32(imgHeight * xScale)
    xNewWidth = Convert.ToInt32(imgWidth * xScale)

    backBuffer = New Bitmap(xNewWidth, xNewHeight, Drawing.Imaging.PixelFormat.Format32bppRgb)
    backBufferGraphics = Graphics.FromImage(backBuffer)
    backBufferGraphics.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
    backBufferGraphics.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
    backBufferGraphics.DrawImage(thisImage, 0, 0, xNewWidth, xNewHeight)

    thisImage.Dispose()
    fi = Nothing

    If DestinationPath <> "" Then
     sFilename = IO.Path.Combine(DestinationPath, IO.Path.GetFileName(sFilename))
    End If

    backBuffer.Save(sFilename, imgFormat)

   Catch ex As Exception

    thisImage.Dispose()
    fi = Nothing
    Throw New Exception(ex.Message)

   End Try

  End Sub

  Public Function GetAString(ByVal Value As Object) As String
   If Value Is Nothing Then
    Return ""
   Else
    If Value Is DBNull.Value Then
     Return ""
    Else
     Return CType(Value, String)
    End If
   End If
  End Function

  Public Function GetABoolean(ByVal x As Object) As Boolean
   If x Is Nothing Then
    Return False
   Else
    If x Is DBNull.Value Then
     Return False
    Else
     Try
      Return CType(x, Boolean)
     Catch ex As Exception
      If TypeOf x Is String Then
       If CType(x, String).ToLower = "on" Then
        Return True
       ElseIf CType(x, String).ToLower = "off" Then
        Return False
       ElseIf CType(x, String).ToLower = "yes" Then
        Return True
       ElseIf CType(x, String).ToLower = "no" Then
        Return False
       ElseIf CType(x, String) = "1" Then
        Return True
       ElseIf CType(x, String) = "0" Then
        Return False
       End If
      End If
      Return False
     End Try
    End If
   End If
  End Function

  Public Sub SimpleLog(ByVal ParamArray Messages As String())

   Dim LogPath As String = DotNetNuke.Common.HostMapPath & "\Questionnaire\Log"
   If Not IO.Directory.Exists(LogPath) Then
    IO.Directory.CreateDirectory(LogPath)
   End If
   Dim File As String = IO.Path.Combine(LogPath, "Log-" & Now.Year.ToString & "-" & Now.Month.ToString & ".txt")
   Dim sw As IO.StreamWriter = Nothing
   Try
    sw = New IO.StreamWriter(File, True)
    Dim Message As String
    For Each Message In Messages
     sw.Write(Format(Now, "dd HH:mm:ss.ff") & " ")
     sw.WriteLine(Message)
    Next
    sw.Flush()
   Catch ex As Exception
   Finally
    sw.Close()
    sw = Nothing
   End Try

  End Sub

 End Module

 Public Structure FilterField
  Public FieldId As String
  Public FieldName As String
  Public Values As Hashtable

  Public Sub New(ByVal FilterFieldId As String, ByVal FilterFieldName As String)
   FieldId = FilterFieldId
   FieldName = FilterFieldName
   Values = New Hashtable
  End Sub
 End Structure
End Namespace